package com.atguigu.gmall.seckill.biz;

import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.seckill.service.SeckillGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.CompositeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2024/10/19 5:57
 */
@Slf4j
@Component
public class LocalCache {
    private Map<Long, SeckillGoods> map = new ConcurrentHashMap<>();
    @Autowired
    SeckillGoodsService seckillGoodsService;
    //map是空的,需要同步数据
    private void syncData() {
        log.info("map是空的,需要同步数据");
        List<SeckillGoods> secKillList = seckillGoodsService.getSecKillList();
        setCache(secKillList);
    }

    //设置本地缓存
    public void setCache(List<SeckillGoods> goodsList) {
        log.info("设置本地缓存....");
        goodsList.forEach(item -> {
            map.put(item.getSkuId(), item);

        });
    }

    //从本地缓存中拿商品详情
    public SeckillGoods getSeckillGoodsDetail(Long skuId) {
        log.info("从本地缓存中拿:{}的商品详情"+skuId);
        SeckillGoods seckillGoods = map.get(skuId);
        if (seckillGoods == null) {
            if (!map.isEmpty()) {
                //表明map中没有这个skuId
                return null;
            } else {
                //表明map为空,需要同步数据
                syncData();
                //同步完成后再拿
                return map.get(skuId);
            }
        }
        //seckillGoods不为空
        return seckillGoods;
    }

    //从本地缓存拿商品列表
    public List<SeckillGoods> getAllSeckillGoods(){
        log.info("从本地缓存拿商品列表");
        if (map.isEmpty()){
            //同步一下数据
            syncData();
        }
        List<SeckillGoods> seckillGoodsList = map.values().stream()
                .sorted((o1, o2) -> {
                    return o1.getStartTime().compareTo(o2.getStartTime());
                })
                .collect(Collectors.toList());
        return seckillGoodsList;
    }
}
